package com.origin.onlinesys.web.controllers.modules.interviewsys;

import com.origin.onlinesys.common.controllers.BaseController;
import com.origin.onlinesys.domain.modules.interviewsys.InterviewerInfo;
import com.origin.onlinesys.domain.modules.interviewsys.InterviewerTrace;
import com.origin.onlinesys.domain.modules.interviewsys.SourceCount;
import com.origin.onlinesys.service.modules.interviewsys.impl.InterviewerInfoServiceImpl;
import com.origin.onlinesys.service.modules.interviewsys.impl.InterviewerTraceServiceImpl;
import com.origin.onlinesys.service.modules.poi.InterviewInfoAndTracePoi;
import com.origin.onlinesys.web.utils.Constants;
import com.origin.onlinesys.web.utils.WebUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * Created by Administrator on 2015/1/23 0023.
 * 面试者
 */
@Controller
@RequestMapping(value = "/management/interview")
public class InterviewsysController extends BaseController {
    @Autowired
    private InterviewerInfoServiceImpl service;

    @Autowired
    private InterviewInfoAndTracePoi infoAndTracePoi;

    @Autowired
    private InterviewerTraceServiceImpl traceService;

    @RequestMapping(value = "/findByPage")
    public @ResponseBody
    Map findByPage(String search,int pageNum,String startDate,String endDate){
        if(startDate != null) startDate = startDate+" 00:00:00";
        if(endDate != null)endDate = endDate+" 23:59:00";
        String varZoneId = WebUtils.getAccount().getQueryZoneId();
        Pattern pattern = Pattern.compile("^[0-9]{1,11}");
        if(search != null && search.length()>0){
            search = search.trim();
            if(pattern.matcher(search).matches())
                return service.selectByJoinAndPage(null,pageNum,pageSize,null,search,null,varZoneId,startDate,endDate,null,Constants.timeout);
            else
                return service.selectByJoinAndPage(null,pageNum,pageSize,null,null,search,varZoneId,startDate,endDate,null,Constants.timeout);
        }
        return service.selectByJoinAndPage(null,pageNum, pageSize, null, null, null,varZoneId,startDate,endDate,null,Constants.timeout);
    }

    @RequestMapping(value = "/findAll")
    public
    @ResponseBody
    List<InterviewerInfo> findAll() {
        return service.selectAllInterv();
    }

    @RequestMapping(value = "/findByWhere")
    public
    @ResponseBody
    List<InterviewerInfo> findByWhere(@ModelAttribute InterviewerInfo info) {
        return service.selectByWhere(info);
    }

    @RequestMapping(value = "/findById")
    public @ResponseBody
    InterviewerInfo findById(String id){
        return service.selectById(id);
    }

    @RequestMapping(value = "/findByUserId")
    public @ResponseBody
    Map selectByUserId(String search,int pageNum,String startDate,String endDate,String userId,String sitId){
        SimpleDateFormat searchSdf = new SimpleDateFormat("yyyy-MM-dd");
        startDate = startDate == null?searchSdf.format(new Date())+" 00:00:00":startDate+" 00:00:00";
        if(endDate != null)endDate = endDate+" 23:59:00";
        if(userId == null)userId = WebUtils.getUserId();
        Pattern pattern = Pattern.compile("^[0-9]{1,11}");
        if(search != null && search.length()>0){
            search = search.trim();
            if(pattern.matcher(search).matches())
                return service.selectByJoinAndPage(sitId,pageNum,pageSize,userId,search,null,null,startDate,endDate,"true",-1);
            else
                return service.selectByJoinAndPage(sitId,pageNum,pageSize,userId,null,search,null,startDate,endDate,"true",-1);
        }
        return service.selectByJoinAndPage(sitId,pageNum, pageSize, userId, null, null,null,startDate,endDate,"true",-1);
    }

    @RequestMapping(value = "/selectCountSource")
    public @ResponseBody
    List<SourceCount> selectCountSource(String startDate,String endDate,String userId){
        return service.selectCountSource(startDate,endDate,userId);
    }

    @RequestMapping(value = "/countAdd")
    public @ResponseBody
    Map countAdd(String startDate,String endDate,String userId){
        return service.countAdd(startDate,endDate,userId);
    }
    @RequestMapping(value = "/add")
    public @ResponseBody
    int addInterview(@ModelAttribute InterviewerInfo info,String sitName,String note) {
        if(WebUtils.getUserId() == null) return 0;
        String visitId=null;InterviewerInfo bean = service.selectByPhoneNum(info.getPhoneNum(),WebUtils.getAccount().getQueryZoneId());
        if(bean != null){
            try {
                long cha = new Date().getTime()
                        - sdf.parse(bean.getCreateTime()).getTime();
                if(cha >= 1000*60*60*24*Constants.timeout  || "2".equals(bean.getState())){
                    info.setCreateTime(sdf.format(new Date()));
                    info.setUserId(WebUtils.getUserId());
                    info.setId(bean.getId());
                    info.setState("1");
                    service.updateInterv(info);
                    visitId = bean.getId();
                }else{return 1;}
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }else{
            //添加面试者
            info.setCreateTime(sdf.format(new Date()));
            info.setUserId(WebUtils.getUserId());
            service.insertInterv(info);
            visitId = info.getId();
        }
        //添加追踪记录
        InterviewerTrace trace = new InterviewerTrace();
        trace.setIntervId(visitId);
        trace.setUserId(WebUtils.getUserId());
        trace.setVisitTime(sdf.format(new Date()));
        trace.setNote(note);
        trace.setSituId(sitName);
        traceService.insertTrace(trace);
        return 0;
    }

    @RequestMapping(value = "/findInfo")
    public @ResponseBody
    InterviewerInfo findInfo(String id){
        return service.selectInfo(id);
    }
    @RequestMapping(value = "/update")
    public @ResponseBody
    int updateInterview(InterviewerInfo info) {
        return service.updateInterv(info);
    }
    @RequestMapping(value = "/del")
    public @ResponseBody
    String deleteInterview(String id) {
        service.delteInterv(id);
        return "1";
    }
    @RequestMapping(value = "/uploadExcel",method = RequestMethod.POST)
    public @ResponseBody
    Object uploadExcel(HttpServletRequest request){
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        /**页面控件的文件流**/
        MultipartFile multipartFile = multipartRequest.getFile("file");
        /**获取文件的后缀**/
        String suffix = multipartFile.getOriginalFilename().substring
                (multipartFile.getOriginalFilename().lastIndexOf("."));
        List<String> suffixList = new ArrayList<String>();
        if(suffix != null && suffix.indexOf("xls") < 0 ){suffixList.add("您上传的文件类型不对");return suffixList;}
        /**拼成完整的文件保存路径加文件**/
        String fileName = this.getUploadPath("interviewerInfo",suffix);
        File file = new File(fileName);
        try {
            multipartFile.transferTo(file);
            Object obj =  infoAndTracePoi.insertInterviewByXls(fileName,WebUtils.getAccount().getQueryZoneId(), Constants.timeout);
            if(obj instanceof List){
                file.delete();return obj;
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    @RequestMapping(value = "/findLatelyTrace")
    public @ResponseBody
    InterviewerInfo findLatelyTrace(){
        return service.selectLatelyTrace(WebUtils.getUserId());
    }

    @RequestMapping(value = "/distill")
    public @ResponseBody
    int distill(String id){
        InterviewerInfo info = new InterviewerInfo();
        info.setId(id);info.setUserId(WebUtils.getUserId());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        info.setCreateTime(sdf.format(new Date()));info.setState("1");
        return service.updateInterv(info);
    }

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    @RequestMapping(value = "/excelShowData")
    public @ResponseBody
    List<InterviewerInfo> excelShowData(String startDate,String endDate,String userId){
        boolean userPer =  getUserPer();
        if(userId == null){userId = WebUtils.getUserId();}else if((userId == null&&userPer)||"".equals(userId)){userId = null;}
        if("true".equals(startDate)){startDate = dateFormat.format(new Date());
            endDate = dateFormat.format(new Date());}
        try {
            Date start = dateFormat.parse(startDate);
            Date end = dateFormat.parse(endDate);
            long a = 1000*60*60*24*30L;
            if((end.getTime()-start.getTime())<0 || (end.getTime()-start.getTime())>a)return null;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(startDate != null)startDate = startDate+" 00:00:00";if(endDate != null)endDate = endDate+" 23:59:00";
        return service.excelShowDate(userId,WebUtils.getAccount().getQueryZoneId(),startDate,endDate);
    }

    @RequestMapping(value = "/exportExcel")
    public void exprotExcel(HttpServletResponse response,String startDate,String endDate,String userId,String userName){
        boolean userPer =  getUserPer();
        if(userId == null){userId = WebUtils.getUserId();}else if((userId == null&&userPer)||"".equals(userId)){userId = null;}
        StringBuilder sb = new StringBuilder("".equals(userName)?WebUtils.getZoneName():userName);
        sb.append(startDate);sb.append("号0点");sb.append("到");sb.append(endDate);sb.append("号23点");sb.append("面试情况.xls");
        try {
            response.setHeader("Content-disposition",
                    "attachment;filename="+new String(sb.toString().getBytes(),"iso_8859_1"));
            response.setContentType("application/vnd.ms-excel");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            Date start = dateFormat.parse(startDate);
            Date end = dateFormat.parse(endDate);
            long a = 1000*60*60*24*30L;
            if((end.getTime()-start.getTime())<0 || (end.getTime()-start.getTime())>a)return;
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if(startDate != null)startDate = startDate+" 00:00:00";if(endDate != null)endDate = endDate+" 23:59:00";
        List<InterviewerInfo> infoList = service.excelSelectInterview(userId,WebUtils.getAccount().getQueryZoneId(),startDate,endDate);
        List<InterviewerTrace> traceList = traceService.excelSelectInterview(userId,WebUtils.getAccount().getQueryZoneId(),startDate,endDate);
        Map traceMap = new HashMap();List<InterviewerTrace> newlist;
        for(InterviewerInfo info:infoList){
            newlist = new ArrayList<InterviewerTrace>();
            for(InterviewerTrace bean:traceList){
                if(info.getId().equals(bean.getIntervId()))newlist.add(bean);
            }
            traceMap.put(info.getId(),newlist);
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH.mm");
        //建立新HSSFWorkbook对象 
        HSSFWorkbook wb = new HSSFWorkbook();
        //建立新的sheet对象
        HSSFSheet sheet = wb.createSheet("导出时间"+simpleDateFormat.format(new Date()));
        HSSFRow headRow = sheet.createRow(0);
        //设置行高
        headRow.setHeight((short)(30*20));
        //设置表头的值
        List list = new ArrayList();
        list.add("日期");list.add("姓名");list.add("电话");list.add("学历");list.add("来源");list.add("咨询师");
        list.add("第一次联系时间");list.add("情况");list.add("备注");list.add("第二次联系时间");list.add("情况");
        list.add("备注");list.add("第三次联系时间");list.add("情况");list.add("备注");
        for(int i = 0;i<list.size();i++){
            //设置单元格的宽度
            sheet.setColumnWidth(i, 16*256);
            //给每个单元格设置值
            HSSFCell cell = headRow.createCell(i);
            cell.setCellValue(list.get(i).toString());
        }
        //设置表格内容
        for(int i = 0;i<infoList.size();i++){
            //在sheet里创建一行，参数为行号
            HSSFRow row = sheet.createRow(i+1);
            //设置行高
            row.setHeight((short)(30*20));
            HSSFCell dateCell = row.createCell(0);dateCell.setCellValue(infoList.get(i).getCreateTime());
            HSSFCell nameCell = row.createCell(1);nameCell.setCellValue(infoList.get(i).getRealName());
            HSSFCell phoneCell = row.createCell(2);phoneCell.setCellValue(infoList.get(i).getPhoneNum());
            HSSFCell eduCell = row.createCell(3);eduCell.setCellValue(infoList.get(i).getEduName());
            HSSFCell enrCell = row.createCell(4);enrCell.setCellValue(infoList.get(i).getSourceName());
            HSSFCell userCell = row.createCell(5);userCell.setCellValue(infoList.get(i).getUserName());
            List<InterviewerTrace> traceList1 = (List<InterviewerTrace>)traceMap.get(infoList.get(i).getId());
            for(int j = 0;j<traceList1.size();j++){
                HSSFCell visitTimeCell = row.createCell(3*j+6);visitTimeCell.setCellValue(traceList1.get(j).getVisitTime());
                HSSFCell situIdCell = row.createCell(3*j+7);situIdCell.setCellValue(traceList1.get(j).getSituationName());
                HSSFCell noteCell = row.createCell(3*j+8);noteCell.setCellValue(traceList1.get(j).getNote());
            }
        }
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            wb.write(out);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {if(out !=null) out.close();} catch (IOException e) {
                e.printStackTrace();
            }
        }
        return;
    }

    @RequestMapping(value = "/phoneNumHave")
    @ResponseBody
    public boolean findByPhoneNum(String phone){
        InterviewerInfo bean = service.selectByPhoneNum(phone,WebUtils.getAccount().getQueryZoneId());
        if(bean == null) return true;return false;
    }

    public boolean getUserPer(){
        if("admin".equals(WebUtils.getAccount().getRoleName()) || "phoneAdmin".equals(WebUtils.getAccount().getRoleName())){
            return true;
        }
        return false;
    }
}